/*!
	\copyright  Copyright (c) 2023 Qualcomm Technologies International, Ltd.
	            All Rights Reserved.
	            Qualcomm Technologies International, Ltd. Confidential and Proprietary.
	\file 		storage_manager.c
	\brief      Storage manager implementation
*/

#include "storage_manager_config_types.h"
#include "storage_manager_interface.h"
#include <panic.h>

storage_mgr_buffer_handle_t StorageManager_OpenBuffer(storage_mgr_config_data_t config, const storage_mgr_event_if * event_if)
{
	storage_mgr_buffer_handle_t handle = NULL;
	if (config)
	{
		const storage_mgr_interface_t * interface = StorageManager_GetSingletonInterfaceByType(config->type);
		handle = interface->StorageManager_OpenBuffer(&config->address, event_if);

		if (handle)
		{
			handle->interface = interface;
		}
	}
	return handle;
}

bool StorageManager_LoadData(storage_mgr_buffer_handle_t source, uint32 offset, uint8 * dest, size_t bytes)
{
	PanicNull(source);
	return source->interface->StorageManager_LoadData(source, offset, dest, bytes);
}

bool StorageManager_SaveData(storage_mgr_buffer_handle_t dest, uint32 offset, const uint8 * source, size_t bytes)
{
	PanicNull(dest);
	return dest->interface->StorageManager_SaveData(dest, offset, source, bytes);
}

void StorageManager_CloseBuffer(storage_mgr_buffer_handle_t buffer)
{
	PanicNull(buffer);
	PanicFalse(buffer->interface->StorageManager_CloseBuffer(buffer));
}

void StorageManager_ForceCloseAllBuffersOfStorage(storage_mgr_type_t type)
{
	const storage_mgr_interface_t * interface = StorageManager_GetSingletonInterfaceByType(type);
	PanicFalse(interface->StorageManager_ForceCloseAllBuffers());
}

void StorageManager_ForceCloseAllBuffers(void)
{
	size_t num_instances = StorageManager_GetSingletonInstanceTableSize();
	const singleton_instance_t * all_instances = StorageManager_GetSingletonInstanceTable();

	for (unsigned i = 0; i < num_instances; i++)
	{
		if ( all_instances[i].is_initialized )
		{
			PanicFalse( all_instances[i].interface->StorageManager_ForceCloseAllBuffers() );
		}
	}
}

size_t StorageManager_GetBufferSize(storage_mgr_buffer_handle_t buffer)
{
	PanicNull(buffer);
	return buffer->interface->StorageManager_GetBufferSize(buffer);
}